package com.web.controller.system;

import com.common.constant.Constants;
import com.common.core.domain.AjaxResult;
import com.common.core.domain.entity.SysMenu;
import com.common.core.domain.entity.SysRole;
import com.common.core.domain.entity.SysUser;
import com.common.core.domain.model.LoginBody;
import com.common.core.domain.model.LoginUser;
import com.common.utils.SecurityUtils;
import com.framework.web.service.SysLoginService;
import com.framework.web.service.SysPermissionService;
import com.framework.web.service.TokenService;
import com.system.service.ISysMenuService;
import com.system.service.ISysRoleService;
import com.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@Api(tags = "A认证模块")
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        Integer type = loginBody.getType();
        String username = loginBody.getUsername();

        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        AjaxResult ajax = AjaxResult.success();
        ajax.put(Constants.TOKEN, token);

        // 登录成功后再取用户信息判断角色
        SysUser sysUser = userService.selectUserByUserName(username);
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        //评审人员入口
        if (type == 1){
            //评审人员入口登录,但用户角色是评审专家  -> 判断这个人的身份是不是只包含评审专家，如果是只有一个角色, 并且是专家角色，否则不允许登录
            boolean onlyReviewer = roles.size() == 1 &&  roles.contains("biz_pszj");
            if (onlyReviewer){
                return AjaxResult.error("评审专家仅可通过专家入口登录");
            }
            //如果不是评审专家，则获取默认角色
            Long defaultRoleId = sysUser.getDefaultRoleId();
            SysRole role = roleService.selectRoleKeyById(defaultRoleId);

            ajax.put("defaultRoleName",role.getRoleName());
            ajax.put("defaultRoleKey",role.getRoleKey());
        //评审专家入口
        } else if (type == 2) {
            //具有评审专家角色才能进入
            boolean hasReviewerRole = roles.contains("biz_pszj");
            if (!hasReviewerRole){
                return AjaxResult.error("非评审专家用户不能通过此入口登录");
            }

            ajax.put("defaultRoleName","评审专家");
            ajax.put("defaultRoleKey","biz_pszj");
        }else {
            return AjaxResult.error("无效的登录类型");
        }
        
        return ajax;
    }



    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @ApiOperation(value = "用户信息")
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        if (!loginUser.getPermissions().equals(permissions)) {
            loginUser.setPermissions(permissions);
            tokenService.refreshToken(loginUser);
        }
        //角色为空,获取defaultRoleId字段对应角色
        if (roles == null || roles.size() == 0){
            SysRole role = roleService.selectRoleKeyById(user.getDefaultRoleId());
            roles.add(role.getRoleKey());
        }

        //权限集合为空,获取defaultRoleId字段对应角色 所拥有的权限
        if (permissions == null || permissions.size() == 0){
            Set<String> perSet  = menuService.selectMenuPermsByRoleId(user.getDefaultRoleId());
            permissions.addAll(perSet);
            //权限加入到登录人身上
            loginUser.setPermissions(permissions);
            //刷新缓存
            tokenService.refreshToken(loginUser);
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters(String roleKey)
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId,roleKey);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
